package com.ysd.lis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysd.common.Result;
import com.ysd.lis.entity.*;
import com.ysd.lis.mapper.sys.*;
import com.ysd.lis.request.FindDeptartmentNamesParam;
import com.ysd.lis.request.OrgDepartmentParam;
import com.ysd.lis.request.OrganizationPageParam;
import com.ysd.lis.service.SysOrgDepartmentService;
import com.ysd.lis.service.SysOrganizationService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * cold_chain.t_org_department 服务实现类
 * </p>
 *
 * @author Peng
 * @since 2021-10-08
 */
@Service
public class SysOrgDepartmentServiceImpl extends ServiceImpl<SysOrgDepartmentMapper, SysOrgDepartment> implements SysOrgDepartmentService {
    @Autowired
    SysOrgDepartmentMapper sysOrgDepartmentMapper;

    @Autowired
    SysOrganizationService sysOrganizationService;


    @Autowired
    SysUserDeptMapper sysUserDeptMapper;
    @Autowired
    SysUserMapper sysUserMapper;

    @Autowired
    SysInterfaceMapper sysInterfaceMapper;


    @Override
    public Result findDepartmentListByOrgId(String orgId) {
        List<Map<String, Object>> list = sysOrgDepartmentMapper.findDepartmentListByOrgId(orgId);
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("deptList", list);
        return Result.succ(1, "获取数据成功", resultMap);
    }

    @Override
    public Result addDepartment(SysOrgDepartment sysOrgDepartment) {
        int i = sysOrgDepartmentMapper.insert(sysOrgDepartment);
        Map<String, Object> resultMap = new HashMap<>();
        if (i == 1) {
            resultMap.put("deptId", sysOrgDepartment.getId());
            return Result.succ(1, "保存成功", resultMap);
        } else {
            return Result.fail("添加失败");
        }
    }

    @Override
    public Result editDepartment(SysOrgDepartment sysOrgDepartment) {
        int i = sysOrgDepartmentMapper.updateById(sysOrgDepartment);
        Map<String, Object> resultMap = new HashMap<>();
        if (i == 1) {
            resultMap.put("deptId", sysOrgDepartment.getId());
            return Result.succ(1, "修改成功", resultMap);
        } else {
            return Result.fail("修改失败");
        }
    }

    @Override
    public Result deleteDepartment(SysOrgDepartment sysOrgDepartment) {
        OrganizationPageParam organizationPageParam = new OrganizationPageParam();
        BeanUtil.copyProperties(sysOrgDepartment, organizationPageParam);
        organizationPageParam.setOrgDeptType("2");
        return sysOrganizationService.deleteOrgOrDept(organizationPageParam);
    }

    @Override
    public Result findDepartmentList(OrgDepartmentParam orgDepartmentParam) {
        Map returnMap = new HashMap();
        LambdaQueryWrapper<SysOrgDepartment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysOrgDepartment::getDelFlag, 0).eq(StringUtils.isNotBlank(orgDepartmentParam.getOrgId()), SysOrgDepartment::getOrgId, orgDepartmentParam.getOrgId());
        if (StringUtils.isNotBlank(orgDepartmentParam.getName())) {
            lambdaQueryWrapper.like(SysOrgDepartment::getName, orgDepartmentParam.getName());
        }
        if (StringUtils.isNotBlank(orgDepartmentParam.getCode())) {
            lambdaQueryWrapper.like(SysOrgDepartment::getCode, orgDepartmentParam.getCode());
        }
        if (StringUtils.isNotBlank(orgDepartmentParam.getOrgId())) {
            lambdaQueryWrapper.like(SysOrgDepartment::getOrgId, orgDepartmentParam.getOrgId());
        }
        if (StringUtils.isNotBlank(orgDepartmentParam.getKeywords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysOrgDepartment::getName, orgDepartmentParam.getKeywords()).or().like(SysOrgDepartment::getCode, orgDepartmentParam.getKeywords()).or().like(SysOrgDepartment::getInputCode, orgDepartmentParam.getKeywords()));
        }
        List<SysOrgDepartment> sysOrgDepartments = sysOrgDepartmentMapper.selectList(lambdaQueryWrapper);
        returnMap.put("deptList", sysOrgDepartments);
        return Result.succ(1, "获取数据成功", returnMap);
    }

    @Override
    public Result findDeptTree(OrgDepartmentParam orgDepartmentParam) {
        Map returnMap = new HashMap();
        String orgId = orgDepartmentParam.getOrgId();
        String orgName = orgDepartmentParam.getOrgName();
        LambdaQueryWrapper<SysOrgDepartment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysOrgDepartment::getDelFlag, 0).eq(SysOrgDepartment::getOrgId, orgId);
        List<SysOrgDepartment> sysOrgDepartments = sysOrgDepartmentMapper.selectList(lambdaQueryWrapper);

        List<Map> parentTree = new ArrayList<>();
        for (SysOrgDepartment dt : sysOrgDepartments) {
            if (StringUtils.isBlank(dt.getParentId()) || orgId.equals(dt.getParentId())) {
                Map map = new HashMap();
                map.put("id", dt.getId());
                map.put("name", dt.getName());
                map.put("code", dt.getCode());
                map.put("orgId", dt.getOrgId());
                map.put("parentId", orgId);
                map.put("parentName", orgName);
                parentTree.add(map);
            }
        }
        for (Map m : parentTree) {
            List<Map> child = getChild(m, sysOrgDepartments);
            m.put("children", child);
        }

        returnMap.put("deptList", parentTree);
        return Result.succ(1, "获取数据成功", returnMap);
    }


    @Override
    public Result findDepartmentUserListByOrgId(OrgDepartmentParam orgDepartmentParam) {
        //获取此机构下的所以部门
        LambdaQueryWrapper<SysOrgDepartment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrgDepartment::getDelFlag, 0).eq(SysOrgDepartment::getOrgId, orgDepartmentParam.getOrgId());
        List<SysOrgDepartment> departmentList = this.list(queryWrapper);

        List<String> deptIds = departmentList.stream().map(SysOrgDepartment::getId).collect(Collectors.toList());

        //获取中间表数据
        LambdaQueryWrapper<SysUserDept> qWrapper = new LambdaQueryWrapper<>();
        qWrapper.eq(SysUserDept::getDelFlag, 0).in(SysUserDept::getDeptId, deptIds);
        List<SysUserDept> userDeptList = sysUserDeptMapper.selectList(qWrapper);
        List<String> userIds = userDeptList.stream().map(SysUserDept::getUserId).collect(Collectors.toList());
        List<SysUser> userList = sysUserMapper.selectBatchIds(userIds);

        Map<String, Object> map = new HashMap<>();
        for (SysOrgDepartment dept : departmentList) {
            List<String> deptUserIds = userDeptList.stream().filter(ud -> ud.getDeptId().equals(dept.getId())).map(SysUserDept::getUserId).collect(Collectors.toList());
            List<SysUser> uList = new ArrayList<>();
            for (String duid : deptUserIds) {
                uList.add(userList.stream().filter(u -> u.getId().equals(duid)).findFirst().get());
            }
            dept.setUserList(uList);
        }


        return Result.succ(1, "获取数据成功", departmentList);
    }

    @Override
    public Result getDepartmentList(OrgDepartmentParam orgDepartmentParam) {

        LambdaQueryWrapper<SysOrgDepartment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysOrgDepartment::getDelFlag, 0).eq(SysOrgDepartment::getOrgId, orgDepartmentParam.getOrgId());
        if (StringUtils.isNotBlank(orgDepartmentParam.getName())) {
            lambdaQueryWrapper.like(SysOrgDepartment::getName, orgDepartmentParam.getName());
        }
        if (StringUtils.isNotBlank(orgDepartmentParam.getCode())) {
            lambdaQueryWrapper.like(SysOrgDepartment::getCode, orgDepartmentParam.getCode());
        }
        if (StringUtils.isNotBlank(orgDepartmentParam.getKeywords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysOrgDepartment::getName, orgDepartmentParam.getKeywords()).or().like(SysOrgDepartment::getCode, orgDepartmentParam.getKeywords()));
        }
        List<SysOrgDepartment> sysOrgDepartments = sysOrgDepartmentMapper.selectList(lambdaQueryWrapper);

        return Result.succ(1, "获取数据成功", sysOrgDepartments);
    }

    @Override
    public Result getDepartAuthorizementList(OrgDepartmentParam orgDepartmentParam) {
        List<String> deptIdList = new ArrayList<>();
        //通过用户名查出用户信息
        String username = orgDepartmentParam.getUsername();
        SysUser sysUser = null;
        if(ToolsUtils.isNotEmpty(username)){
            LambdaQueryWrapper<SysUser> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(SysUser::getUsername, orgDepartmentParam.getUsername())
                    .eq(SysUser::getDelFlag, 0);
            List<SysUser> sysUsers = sysUserMapper.selectList(userLambdaQueryWrapper);
            if(ToolsUtils.isNotEmpty(sysUsers)){
                 sysUser = sysUsers.get(0);
            }
        }else {
            sysUser = RedisUserManager.getUser();
        }
        if(ToolsUtils.isNotEmpty(sysUser)){
            //根据userid获取SYS_USER_DEPT 表得数据
            LambdaQueryWrapper<SysUserDept> userDeptLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userDeptLambdaQueryWrapper.eq(SysUserDept::getUserId, sysUser.getId())
                    .eq(SysUserDept::getDelFlag, 0);
            List<SysUserDept> sysUserDepts = sysUserDeptMapper.selectList(userDeptLambdaQueryWrapper);
            List<String> collect = sysUserDepts.stream().map(SysUserDept::getDeptId).collect(Collectors.toList());
            deptIdList.addAll(collect);
            //根据userid 获取SYS_USER_DEPARTMENT
            LambdaQueryWrapper<SysUserDepartment> userDepartLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userDepartLambdaQueryWrapper.eq(SysUserDepartment::getUserId, sysUser.getId())
                    .eq(SysUserDepartment::getDelFlag, 0);
            List<SysUserDepartment> sysUserDepartments = sysUserDepartmentMapper.selectList(userDepartLambdaQueryWrapper);
            List<String> collect1 = sysUserDepartments.stream().map(SysUserDepartment::getDeptId).collect(Collectors.toList());
            deptIdList.addAll(collect1);

        }
        List<SysOrgDepartment> sysOrgDepartments = new ArrayList<>();
        if(ToolsUtils.isNotEmpty(deptIdList)){
            sysOrgDepartments = this.listByIds(deptIdList);
        }
        List<String> deptNoList = orgDepartmentParam.getDeptNoList();
        if(ToolsUtils.isNotEmpty(deptNoList)){
            List<String> queryDnoList = new ArrayList<>();
            if(ToolsUtils.isNotEmpty(sysOrgDepartments)){
                //查看sysOrgDepartments中是否存在deptNoList集合中的字符串 如果不存在则添加到queryDnoList中
                for(String deptNo : deptNoList){
                    Optional<SysOrgDepartment> first = sysOrgDepartments.stream().filter(a -> deptNo.equals(a.getCode())).findFirst();
                    if(!first.isPresent()){
                        queryDnoList.add(deptNo);
                    }

                }

            }else {
                queryDnoList.addAll(deptNoList);
            }
            if(ToolsUtils.isNotEmpty(queryDnoList)){
                //根据CODE查询
                LambdaQueryWrapper<SysOrgDepartment> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(SysOrgDepartment::getDelFlag, 0).in(SysOrgDepartment::getCode, queryDnoList);
                List<SysOrgDepartment> orgDepartmentList = sysOrgDepartmentMapper.selectList(queryWrapper);
                if(ToolsUtils.isNotEmpty(orgDepartmentList))
                sysOrgDepartments.addAll(orgDepartmentList);
            }

        }

        return Result.succ(1, "获取数据成功", sysOrgDepartments);
    }
    @Autowired
    SysUserDepartmentMapper sysUserDepartmentMapper;

    /**
     * 获取当前用户所在组织机构的所有科室
     */
    @Override
    public Result findDepartmentListByCurrentUserOrg() {
        SysUser sysUser = RedisUserManager.getUser();
        LambdaQueryWrapper<SysOrgDepartment> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysOrgDepartment::getDelFlag, 0).eq(SysOrgDepartment::getOrgId, sysUser.getOrgId());
        List<SysOrgDepartment> departmentList = this.list(queryWrapper);
        return Result.succ(1, "获取成功", departmentList);
    }

    @Override
    public Result syncOrgDepartments() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String token = request.getHeader("Authorization").replace("Bearer ", "");
        String orgId = RedisUserManager.getStoreOrg("currentOrg" + token);

        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, orgId);
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());

        try {
            if (CollectionUtils.isNotEmpty(collect)) {
                for (String webUrl : collect) {
                    SysOrgDepartment sysOrgDepartment = new SysOrgDepartment();
                    sysOrgDepartment.setOrgId(orgId);
                    String returnMsg1 = HttpUtil.createPost(webUrl + "/public/syncSysDepartment").body(JSONUtil.toJsonStr(sysOrgDepartment)).contentType("application/json").execute().body();
                    JSONObject reportObject = new JSONObject(returnMsg1);
                    JSONObject reportStatus = reportObject.getJSONObject("status");
                    String reportCode = reportStatus.get("code").toString();
                    if ("400".equals(reportCode)) {
                        return Result.fail("接口管理平台异常,请检查");
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("接口管理平台异常,请检查");
        }

        return Result.succ(1, "请求成功", null);
    }

    @Override
    public Result findSysOrgDepartmentList(OrgDepartmentParam orgDepartmentParam) {
        LambdaQueryWrapper<SysOrgDepartment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysOrgDepartment::getDelFlag, 0).eq(StringUtils.isNotBlank(orgDepartmentParam.getOrgId()), SysOrgDepartment::getOrgId, orgDepartmentParam.getOrgId());
        if (StringUtils.isNotBlank(orgDepartmentParam.getName())) {
            lambdaQueryWrapper.like(SysOrgDepartment::getName, orgDepartmentParam.getName());
        }
        if (StringUtils.isNotBlank(orgDepartmentParam.getCode())) {
            lambdaQueryWrapper.like(SysOrgDepartment::getCode, orgDepartmentParam.getCode());
        }
        if (StringUtils.isNotBlank(orgDepartmentParam.getOrgId())) {
            lambdaQueryWrapper.like(SysOrgDepartment::getOrgId, orgDepartmentParam.getOrgId());
        }
        if (StringUtils.isNotBlank(orgDepartmentParam.getKeywords())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysOrgDepartment::getName, orgDepartmentParam.getKeywords()).or().like(SysOrgDepartment::getCode, orgDepartmentParam.getKeywords()));
        }
        List<SysOrgDepartment> sysOrgDepartments = sysOrgDepartmentMapper.selectList(lambdaQueryWrapper);
        return Result.succ(1, "获取数据成功", sysOrgDepartments);
    }

    /*根据科室编号获取科室名称，仅用于显示*/
    @Override
    public Result fingDepartmentNamesByCodes(FindDeptartmentNamesParam input) {
        LambdaQueryWrapper<SysOrgDepartment> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysOrgDepartment::getDelFlag, 0);
        lambdaQueryWrapper.in(SysOrgDepartment::getCode, input.getNos());
        List<SysOrgDepartment> list = sysOrgDepartmentMapper.selectList(lambdaQueryWrapper);
        String nameStr = list.stream().map(SysOrgDepartment::getName).collect(Collectors.joining(","));
        return Result.succ(1, "成功", nameStr);
    }

    private List<Map> getChild(Map m, List<SysOrgDepartment> departmentList) {
        List<Map> result = new ArrayList();
        if (null != departmentList) {
            for (SysOrgDepartment dt : departmentList) {
                if (StringUtils.isNotBlank(dt.getParentId()) && dt.getParentId().equals(m.get("id"))) {
                    Map map = new HashMap();
                    map.put("id", dt.getId());
                    map.put("name", dt.getName());
                    map.put("code", dt.getCode());
                    map.put("orgId", dt.getOrgId());
                    map.put("parentId", dt.getParentId());
                    map.put("parentName", m.get("name"));
                    result.add(map);
                }
            }
        }
        for (Map ma : result) {
            ma.put("children", getChild(ma, departmentList));
        }
        if (result.size() == 0) {
            return null;
        }
        return result;
    }

}
